<script setup>
    import { ElMessage } from "element-plus"
    import { getCurrentInstance, onMounted, ref, reactive, nextTick } from "vue"

    onMounted(() => {
        getUserData(config)
    })
    //获取this
    const { proxy } = getCurrentInstance()
    const list = ref([])
    const tableLabel = reactive([
        {
            prop: "name",
            label: "姓名",
        },
        {
            prop: "age",
            label: "年龄",
        },
        {
            prop: "sexLabel",
            label: "性别",
        },
        {
            prop: "birth",
            label: "出生日期",
            width: 200,
        },
        {
            prop: "addr",
            label: "地址",
            width: 320,
        },
    ])
    //传给api文件夹下面的mockData的数据
    const config = reactive({
        total: 0,
        page: 1,
        name: "",
    })

    const formInline = reactive({
        keyWord: "",
    })

    //dialog模态框的开关
    let dialogVisible = ref(false)

    //接受表格的ref，可用来操作表格（如重置表格内容）
    const formDataRef = ref(null)

    //添加用户使用的数据
    let formUser = reactive({
        name: "",
        sex: "",
        age: "",
        birth: "",
        addr: "",
    })
    const handleClose = (done) => {
        resetForm()
        done()
    }

    const getUserData = async (config) => {
        let res = await proxy.$api.getUserData(config)
        // console.log("userView.list", res)
        config.total = res.count
        list.value = res.list.map((item) => {
            item.sexLabel = item.sex === 0 ? "女" : "男"
            return item
        })
    }

    const changePage = (page) => {
        config.page = page
        getUserData(config)
    }

    const handleSearch = (keyWord) => {
        config.name = keyWord
        getUserData(config)
    }
    //区分编辑和新增
    const action = ref("add")

    const handleAdd = () => {
        dialogVisible.value = true
        action.value = "add"
    }
    //这里是dialog的提交按钮
    const submitForm = (formUser) => {
        formDataRef.value.validate(async (valid) => {
            if (valid) {
                //添加用户
                if (action.value == "add") {
                    // 调用接口保存
                    // console.log("formUser", formUser)
                    let res = await proxy.$api.addUser(formUser)
                    getUserData(config)
                    resetForm()
                    // 关闭弹窗
                    dialogVisible.value = false
                } else {
                    //编辑用户
                    // console.log(formUser)
                    //这里是返回数据给后台，所以把sex变成原本的数字类型
                    formUser.sex == "男"
                        ? (formUser.sex = 1)
                        : (formUser.sex = 0)
                    let res = await proxy.$api.editUser(formUser)
                    getUserData(config)
                    resetForm()
                    // 关闭弹窗
                    dialogVisible.value = false
                }
            } else {
                ElMessage({
                    showClose: true,
                    message: "请输入正确的内容",
                    type: "error",
                })
            }
        })
    }

    //重置按钮
    const resetForm = () => {
        if (formDataRef.value) {
            formDataRef.value.resetFields() // 重置表单验证状态
        }
        formUser.name = ""
        formUser.sex = ""
        formUser.age = ""
        formUser.birth = ""
        formUser.addr = ""
        console.log("重置", formDataRef)
    }

    // 编辑用户
    const handleEdit = (row) => {
        row.sex == "0" ? (row.sex = "女") : (row.sex = "男")
        Object.assign(formUser, row)
        action.value = "edit"
        dialogVisible.value = true

        // 使用 nextTick 确保 DOM 更新后再执行重置操作，把原本的数据映射上去
        nextTick(() => {
            Object.assign(formUser, row)
        })
    }

    //删除用户

    const handleDelete = (row) => {
        ElMessageBox.confirm("确定要删除嘛?")
            .then(async () => {
                await proxy.$api.deleteUser({
                    id: row.id,
                })

                ElMessage({
                    showClose: true,
                    message: "删除成功",
                    type: "success",
                })
                getUserData(config)
            })
            .catch(() => {})
    }
</script>
<template>
    <div class="user-header">
        <el-button type="primary" @click="handleAdd()">+新增</el-button>
        <el-form :inline="true" :model="formInline">
            <el-form-item label="">
                <el-input
                    v-model="formInline.keyWord"
                    placeholder="请输入用户名"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    @click="handleSearch(formInline.keyWord)"
                    >搜索</el-button
                >
            </el-form-item>
        </el-form>
    </div>
    <div class="table">
        <el-table :data="list" style="width: 100%" height="400px">
            <el-table-column
                v-for="item in tableLabel"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
                :width="item.width ? item.width : 125"
            />
            <el-table-column fixed="right" label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)"
                        >编辑</el-button
                    >
                    <el-button
                        size="small"
                        type="danger"
                        @click="handleDelete(scope.row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <div>
            <el-pagination
                class="pager"
                layout="prev, pager, next"
                :total="config.total"
                @current-change="changePage"
            />
        </div>
    </div>
    <!-- 模糊框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="action === 'add' ? '新增用户' : '编辑用户'"
        width="45%"
        :before-close="handleClose"
    >
        <el-form
            ref="formDataRef"
            :model="formUser"
            label-width="100px"
            class="demo-ruleForm"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item
                        label="姓名"
                        prop="name"
                        :rules="[
                            {
                                required: true,
                                message: '请输入姓名',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-input
                            v-model="formUser.name"
                            type="text"
                            autocomplete="off"
                            placeholder="请输入姓名"
                        /> </el-form-item
                ></el-col>
                <el-col :span="12">
                    <el-form-item
                        label="年龄"
                        prop="age"
                        :rules="[
                            {
                                required: true,
                                message: '请输入年龄',
                                trigger: 'blur',
                            },
                            { type: 'number', message: '必须是整数 ' },
                        ]"
                    >
                        <el-input
                            v-model.number="formUser.age"
                            type="text"
                            autocomplete="off"
                            placeholder="请输入年龄"
                        /> </el-form-item
                ></el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item
                        label="性别"
                        prop="sex"
                        :rules="[
                            {
                                required: true,
                                message: '请选择性别',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-select
                            v-model="formUser.sex"
                            class="m-2"
                            placeholder="请选择性别"
                            size="large"
                        >
                            <el-option label="男" value="1" />
                            <el-option label="女" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item
                        label="日期"
                        prop="birth"
                        :rules="[
                            {
                                required: true,
                                message: '请选择日期',
                                trigger: 'blur',
                            },
                        ]"
                    >
                        <el-date-picker
                            v-model="formUser.birth"
                            type="date"
                            placeholder="选择日期"
                            :default-value="new Date(2010, 9, 1)"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </el-col>
                <el-form-item
                    label="地址 "
                    prop="addr"
                    :rules="[
                        {
                            required: true,
                            message: '请输入地址',
                            trigger: 'blur',
                        },
                    ]"
                >
                    <el-input
                        v-model="formUser.addr"
                        type="text"
                        autocomplete="off"
                        placeholder="请输入地址"
                    />
                </el-form-item>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <div
                        style="
                            display: flex;
                            justify-content: center;
                            align-items: center;
                        "
                    >
                        <el-button type="primary" @click="submitForm(formUser)"
                            >提交</el-button
                        >
                        <el-button @click="resetForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<style lang="less" scoped>
    .table {
        position: relative;
        .pager {
            position: absolute !important;
            right: 0;
            margin-top: 20px;
            margin-right: 20px;
        }
    }
    .user-header {
        display: flex;
        justify-content: space-between;
    }
</style>
